import { cloneDeep, isBoolean, isUndefined } from 'lodash';
import { BasicPaginationProps, BasicTableProps } from '../types';
import { LAYOUT, PAGE_SIZE, PAGE_SIZES } from '../const';
import { ComputedRef, ref, watch, unref, computed } from 'vue';

export * from '../types/pagination';

/**
 * 分页
 * @param props
 * @returns
 */
export function usePagination(props: ComputedRef<BasicTableProps>) {
  const configRef = ref<BasicPaginationProps>({});
  const showPagination = ref(false);
  const pageSize = ref(PAGE_SIZE);
  const currentPage = ref(1);

  watch(
    () => props.value.pagination,
    (val) => {
      if (!(isBoolean(val) && val === false)) {
        if (isBoolean(val) || isUndefined(val)) {
          configRef.value = {
            pageSizes: PAGE_SIZES,
            layout: LAYOUT,
            total: 0,
          };
        } else {
          configRef.value = cloneDeep(val);
        }

        showPagination.value = true;
        pageSize.value = unref(configRef).pageSize ?? unref(configRef).defaultPageSize ?? PAGE_SIZE;
      } else {
        showPagination.value = false;
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  const getPaginationProps = computed(() => {
    return { ...unref(configRef) };
  });
  const getMetaInfo = computed(() => {
    if (!unref(showPagination)) {
      return {};
    }
    return {
      pageSize: unref(pageSize),
      currentPage: unref(currentPage),
    };
  });

  const setTotal = (total: number) => {
    configRef.value.total = total;
  };
  const setCurrentPage = (page: number) => {
    currentPage.value = page;
  };

  return {
    showPagination,
    pageSize,
    currentPage,
    getPaginationProps,
    getMetaInfo,
    setTotal,
    setCurrentPage,
  };
}
